package com.dbq.fast.business.main.task;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.util.SpUtil;
import com.dbq.fast.util.SystemUtil;

import java.util.HashMap;
import java.util.Locale;


/**
 * Created by Jean on 2017/12/29.
 */

public class UploadRatingCommentTask {

    private static HttpManager httpManager = HttpManager.getInstance();

    /**
     * 给服务器上传用户反馈
     */
    public static void uploadRatingComments(final Context context, final String comments) {
        if (context == null) return;
        boolean isUploadComments = (boolean) SpUtil.getBoolean("upload_comments_ok", false);
        if (!isUploadComments) {
            final String androidId = SystemUtil.getAndroidId(context.getApplicationContext());
            final String osVersion = SystemUtil.getDeviceOSVersion();
            final String appVersion = SystemUtil.getAppVersionName(context.getApplicationContext());
            final String email = getEmail(context.getApplicationContext());
            HashMap hashMap = new HashMap();
            hashMap.put("android_id", androidId);// android id
            hashMap.put("app_version", appVersion);// app version name
            hashMap.put("os_version", osVersion);// app version name
            hashMap.put("country", Locale.getDefault().getCountry());
            hashMap.put("language", Locale.getDefault().getLanguage());
            hashMap.put("comment", comments);
            hashMap.put("email", email);
            httpManager.getHttpService()
                    .uploadComment(hashMap)
                    .compose(new CommonTransformer<>())
                    .subscribe(s -> {
                        SpUtil.setBoolean("upload_comments_ok", true);
                    }, throwable -> {
                        SpUtil.setBoolean("upload_comments_ok", true);
                    });
        }
        Toast.makeText(App.getContext(), App.getContext().getString(R.string.comment_ok), Toast.LENGTH_SHORT).show();
    }

    static String getEmail(Context context) {
        try {
            AccountManager accountManager = AccountManager.get(context);
            Account account = getAccount(accountManager);

            if (account == null) {
                return null;
            } else {
                return account.name;
            }
        } catch (Exception e) {
        }
        return null;
    }

    private static Account getAccount(AccountManager accountManager) {
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
            account = accounts[0];
        } else {
            account = null;
        }
        return account;
    }
}
